<?php
/**
 * Created by PhpStorm.
 * User: lwt
 * Date: 2018/9/19
 * Time: 15:50
 */

namespace app\api\controller\model;



use EasyWeChat\Factory;
use think\Log;

class WechatModel
{

    public $app;
    private $config = [
        'app_id' => 'your-app-id',         // AppID
        'secret' => 'your-app-secret',     // AppSecret
        'token' => 'your-token',          // Token
        'aes_key' => '',                    // EncodingAESKey，兼容与安全模式下请一定要填写！！！

        'mch_id' => 'your-mch-id',
        'key' => 'key-for-signature',   // API 密钥

        // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
        'cert_path' => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
        'key_path' => 'path/to/your/key',      // XXX: 绝对路径！！！！

        'notify_url' => '默认的订单回调地址',     // 你也可以在下单时单独设置来想覆盖它

        // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
        'response_type' => 'array',

        'log' => [
            'level' => 'debug',
            'file' => ROOT_PATH . '/wechat.log',
        ],
    ];

    /**
     * WechatModel constructor.
     * 0-公众号；1-小程序
     */
    public function __construct($type = 0, $pay = false)
    {
        $wechat_config = Db('gzns_wechat_config')->where('type',$type)->find();
        $this->config['app_id'] = $wechat_config['app_id'];
        $this->config['secret'] = $wechat_config['app_secret'];
        $this->config['token'] = $wechat_config['token'];
        $this->config['aes_key'] = $wechat_config['aes_key'];
        $this->config['mch_id'] = $wechat_config['mch_id'];
        $this->config['key'] = $wechat_config['key'];
        
        $this->config['cert_path'] = ROOT_PATH .''. $wechat_config['cert_path'];
        $this->config['key_path'] = ROOT_PATH .''. $wechat_config['key_path'];
        if ($pay) {
            $this->app = Factory::payment($this->config);
        } else {
            if ($type == 0) {
                $this->app = Factory::officialAccount($this->config);
            }
            if ($type == 1) {
                $this->app = Factory::miniProgram($this->config);
            }
        }
//        if ($type == 0) {
//            $this->app = Factory::officialAccount($this->config);
//        }
//        if ($type == 1) {
//
//        }
    }

    public function buildConfig($apiList=['onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareTimeline', 'onMenuShareAppMessage',],$url)
    {

//        $this->app->jssdk->setUrl(Request::instance()->domain());
        $this->app->jssdk->setUrl($url);

        return $this->app->jssdk->buildConfig($apiList, $debug = false, $beta = false, $json = false);
    }



    public function create_menu($menu = [])
    {
        $res = $this->app->menu->create($menu);
        return $res;
    }
    public function material_list($type, $offset, $count) {
        $res = $this->app->material->list($type, $offset, $count);
        return $res;
    }
    public function visitPage( $from,  $to) {
        $res = $this->app->data_cube->visitPage( $from,  $to);
        return $res;
    }

    public function dailyVisitTrend( $from,  $to) {
        $res = $this->app->data_cube->dailyVisitTrend( $from,  $to);
        return $res;
    }

    public function getXcxCode($path) {
        $response = $this->app->app_code->getUnlimit("1=1", [
            'page' => $path
        ]);
        Log::info('生成小程序码：'.$path);

// 或
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $header = $response->getHeaders();
            if ($header['Content-Type'][0] == 'application/json; charset=UTF-8') {
                $res = $response->toJson();
                throw new \Exception($res);
            }
            $name = "hexiao.png";
            $spath = ROOT_PATH  . 'uploads/' ;
            $filename = $response->saveAs($spath, $name);
            return '/uploads/'.$name;
        }
        return null;

    }

    public function getXcxActivityShareCode($path,$share_user_id,$activity_id) {
        $response = $this->app->app_code->getUnlimit("{$share_user_id},{$activity_id}", [
           'page' => $path
        ]);
        Log::info('生成小程序码：'.$path);

// 或
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $header = $response->getHeaders();
            if ($header['Content-Type'][0] == 'application/json; charset=UTF-8') {
                $res = $response->toJson();
                throw new \Exception($res);
            }
            $name = "activity_share_${share_user_id}.png";
            $spath = ROOT_PATH  . 'uploads/' ;
            $filename = $response->saveAs($spath, $name);
            return '/uploads/'.$name;
        }
        return null;

    }

    public function getXcxActivityHelpCode($path,$share_id,$activity_id,$share_user_id) {
       // $scene = "share_id=${share_id}&share_user_id=${share_user_id}&activity_id=${activity_id}";
        $response = $this->app->app_code->getUnlimit("${share_id},${share_user_id},${activity_id}", [
            'page' => $path
        ]);
        Log::info('生成小程序码：'.$path);

// 或
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $header = $response->getHeaders();
            if ($header['Content-Type'][0] == 'application/json; charset=UTF-8') {
                $res = $response->toJson();
                throw new \Exception($res);
            }
            $name = "activity_help_${share_id}.png";
            $spath = ROOT_PATH  . 'uploads/' ;
            $filename = $response->saveAs($spath, $name);
            return '/uploads/'.$name;
        }

        return null;

    }

    public function getFormId($user_id)
    {
        $form_id = db('gzns_form_id')
            ->where('user_id', $user_id)
            ->where('status', 0)
            ->where('create_time', 'between', [date('Y-m-d H:i:s',(time() - 600000)), date('Y-m-d H:i:s',time())])
            ->order('create_time asc')
            ->limit(1)
            ->value('form_id');
        return $form_id;
    }

    public function useFormId($user_id, $form_id)
    {
        db('gzns_form_id')
            ->where('user_id', $user_id)
            ->where('form_id', $form_id)
            ->update(["status" => 1]);
    }

    public function appointReply($user_id,$openid,$data,$page){
        $form_id = $this->getFormId($user_id);
        if ($form_id) {
            $res = $this->app->template_message->send([
                'touser' => $openid,
                'template_id' => 'zOXt-PJfzYOOv9m9x7Jg8FYRRyVCBXEen9pELsNcrMQ',
                'page' => $page,
                'form_id' => $form_id,
                'data' => [
                    'keyword1' => $data[0], //提问主题
                    'keyword2' => $data[1], //回复人
                    'keyword3' => $data[2], //回复时间
                ]
            ]);
            //使用formId
            $this->useFormId($user_id, $form_id);
        }
    }

    public function vipExpireNotice($user_id,$openid,$data,$page){
        $form_id = $this->getFormId($user_id);
        if ($form_id) {
            $this->app->template_message->send([
                'touser' => $openid,
                'template_id' => 'NtcXli3tJhy6LbIT1CeKUCDpI7Ztlrjwm9CiFyYoNm8',
                'page' => $page,
                'form_id' => $form_id,
                'data' => [
                    'keyword1' => $data[0], //服务名称
                    'keyword2' => $data[1], //开始时间
                    'keyword3' => $data[2], //结束时间
                    'keyword4' => $data[3], //温馨提示
                ]
            ]);
            //使用formId
            $this->useFormId($user_id, $form_id);
        }
    }

    /**
     * @api subAptitude
     * @type post
     * @desc 用户认证提醒
     * @param string username * 用户名
     * @return object RespondVo 封装对象
     */
    public function subAptitude($user_id,$openid,$data,$page){
        $form_id = $this->getFormId($user_id);
        if ($form_id) {
            $this->app->template_message->send([
                'touser' => $openid,
                'template_id' => 'IH_cE41nsC3hOL5dvn0JBtwbSywQL0SV7vXYMIyGlRc',
                'page' => $page,
                'form_id' => $form_id,
                'data' => [
                    'keyword1' => $data[0], //认证人
                    'keyword2' => $data[1], //认证身份
                    'keyword3' => $data[2], //企业名称
                    'keyword4' => $data[3], //认证时间
                    'keyword5' => $data[4], //说明
                ]
            ]);
            //使用formId
            $this->useFormId($user_id, $form_id);
        }
    }

    /**
     * @api aptitudeStatus
     * @type post
     * @desc 企业认证通知
     * @param string username * 用户名
     * @return object RespondVo 封装对象
     */
    public function aptitudeStatus($user_id,$openid,$data,$page){
        $form_id = $this->getFormId($user_id);
        if ($form_id) {
            $this->app->template_message->send([
                'touser' => $openid,
                'template_id' => 'Qw318551a93ylEIGYKKEgyCiVzl7XRr44VlWsONKiCg',
                'page' => $page,
                'form_id' => $form_id,
                'data' => [
                    'keyword1' => $data[0], //联系人
                    'keyword2' => $data[1], //认证类型
                    'keyword3' => $data[2], //企业名称
                    'keyword4' => $data[3], //认证时间
                    'keyword5' => $data[4], //企业状态
                    'keyword6' => $data[5], //备注
                ]
            ]);
            //使用formId
            $this->useFormId($user_id, $form_id);
        }
    }

    /**
     * @api activitySoonStart
     * @type post
     * @desc 课程即将开始提醒
     * @param string username * 用户名
     * @return object RespondVo 封装对象
     */
    public function activitySoonStart($user_id,$openid,$data,$page){
        $form_id = $this->getFormId($user_id);
        if ($form_id) {
            $this->app->template_message->send([
                'touser' => $openid,
                'template_id' => 'VCeF5BYzVwpt-C0uF_KZjcGgvG3aJinem_KyBsn0fcY',
                'page' => $page,
                'form_id' => $form_id,
                'data' => [
                    'keyword1' => $data[0], //课程名称
                    'keyword2' => $data[1], //讲师
                    'keyword3' => $data[2], //地址
                    'keyword4' => $data[3], //上课时间
                    'keyword5' => $data[4], //备注
                ]
            ]);
            //使用formId
            $this->useFormId($user_id, $form_id);
        }
    }

    /**
     * @api cancelActivity
     * @type post
     * @desc 核销成功通知
     * @param string username * 用户名
     * @return object RespondVo 封装对象
     */
    public function cancelActivity($user_id,$openid,$data,$page){
        $form_id = $this->getFormId($user_id);
        if ($form_id) {
            $this->app->template_message->send([
                'touser' => $openid,
                'template_id' => 'RR168SjX8JZuE5mTrJ-yEB9xSQDfuSpFz99SO6Yr3mk',
                'page' => $page,
                'form_id' => $form_id,
                'data' => [
                    'keyword1' => $data[0], //活动名称
                    'keyword2' => $data[1], //核销码/订单号
                    'keyword3' => $data[2], //核销员
                    'keyword4' => date('Y-m-d H:i:s'), //核销时间
                    'keyword5' => $data[3], //备注
                ]
            ]);
            //使用formId
            $this->useFormId($user_id, $form_id);
        }
    }

    /**
     * @api successPay
     * @type post
     * @desc 支付成功
     * @param string username * 用户名
     * @return object RespondVo 封装对象
     */
    public function successPay($user_id,$openid,$data,$page)
    {
        $form_id = $this->getFormId($user_id);
        if ($form_id) {
            $this->app->template_message->send([
                'touser' => $openid,
                'template_id' => 'QdYK8f_LR7fRmxMEGkpX15zHJoorNb1mAecp03WEhBs',
                'page' => $page,
                'form_id' => $form_id,
                'data' => [
                    'keyword1' => $data[0], //订单号
                    'keyword2' => $data[1], //客户名称
                    'keyword3' => $data[2], //支付金额
                    'keyword4' => date('Y-m-d H:i:s'), //支付时间
                    'keyword5' => $data[3], //温馨提示
                ]
            ]);
            //使用formId
            $this->useFormId($user_id, $form_id);
        }
    }
}